﻿using System.Net;
using System.IO;
using HtmlAgilityPack;
using System;
using System.Windows.Forms;
namespace taobaoSpider
{
    /// <summary>
    /// 模板的类型
    /// </summary>
    public enum MobanKind
    {

    }

    public class HtmlHttp
    {
        /// <summary>
        /// 请求淘宝服务器获取店铺是否存在
        /// </summary>
        /// <param name="urlNum"></param>
        /// <returns>返回四种可能结果：1：远程服务器返错误(异常抛出) 2：操作超时(异常抛出)  3：店铺浏览(请求店铺不存在)  4：正常内容 5：请求被中止: 连接被意外关闭。</returns> 
        public string GetHtmlContent(string url)
        {
            string ret = "";
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Timeout = 5000;
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                Stream receiveStream = res.GetResponseStream();

                StreamReader sr = new StreamReader(receiveStream, System.Text.Encoding.Default);
                ret = sr.ReadToEnd();
                sr.Close();
                res.Close();
            }
            catch (WebException ex)
            {
                GlobalFun.WriteErrorLog("HtmlHttp:GetHtmlContent():WebException", ex.Message);
                if (ex.Message.Contains("请求被中止") || ex.Message.Contains("未能解析此远程名称"))
                {//将另外未知错误归类到此类中,让路由器重启.
                    ret = "无法连接到远程服务器";
                    return ret;
                }
                return ret = ex.Message;
            }
            catch (Exception ex)
            {//多路捕获异常。
                GlobalFun.WriteErrorLog("HtmlHttp:GetHtmlContent():Exception", ex.Message);
                return ret = "IO读取异常";
            }
            return ret;
        }

        public HtmlAgilityPack.HtmlDocument ParseToHtml(string html)
        {
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(html);
            return htmlDoc;
        }

        #region
        /// <summary>
        /// 模拟浏览器访问来获取HTML内容
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        //public void GetHtmlContentByBrowse(string url)
        //{
        //    browser.Navigated += new WebBrowserNavigatedEventHandler(browser_Navigated);
        //    loading = true;  //表示正在加载
        //    browser.Navigate(url);
        //    while (loading)
        //    {
        //        Application.DoEvents();//等待本次加载完毕才执行下次循环.
        //    } 
        //}
        //void browser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        //{
        //    //Stream htmlStream = browser.DocumentStream;  //获取到的html流.
        //   // StreamReader sr = new StreamReader(htmlStream, System.Text.Encoding.Default);
        //    string htmlContent = browser.DocumentText;
        //    if (htmlContent.Contains("shopId"))
        //    {
        //        shopId = htmlContent.Substring(htmlContent.IndexOf("shopId"), 30).Split('=', ';')[1];
        //        loading = false;
        //    }
        //    //在加载完成后,将该变量置为false,下一次循环随即开始执行.
        //}

        /// <summary>
        /// 将页面返回的串格式为HTML文件形式。
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>


        /// <summary>
        /// 将返回页面内容解析后返回到店铺实体类。
        /// </summary>
        /// <param name="htmlDoc"></param>
        /// <param name="kind"></param>
        /// <returns></returns>
        //public TBWS.dianpu ParseHtmlToDianpu(string htmlContent)
        //{
        //    TBWS.dianpu dp = new TBWS.dianpu();
        //    HtmlAgilityPack.HtmlDocument htmlDoc = ParseToHtml(htmlContent);
        //    string title = "";
        //    //通过title来判断是天猫Tmall还是淘宝店铺。
        //    try
        //    {
        //        title = htmlDoc.DocumentNode.SelectNodes("//title")[0].InnerText.Trim();
        //    }
        //    catch (Exception ex)
        //    {
        //        GlobalFun.Write("err.log", false, htmlContent);
        //        System.Windows.Forms.MessageBox.Show(ex.Message);
        //        return null;
        //    }
        //    //htmlContent.Contains("2012新版旺铺") || htmlContent.Contains("本店所使用旺铺版本") || htmlContent.Contains("旺铺旗舰版") || htmlContent.Contains("旺铺拓展版")
        //    if ((title.Contains("淘宝网")||title.Contains("天猫Tmall.com")))
        //    {
        //        dp.shopTitle = title.Split('-')[1];
        //        string script = htmlDoc.DocumentNode.SelectNodes("//script")[0].InnerText;
        //        try
        //        {
        //            dp.shopId = script.Substring(script.IndexOf("shopId"), 30).Split(new char[] { ':', ',', '"' })[3];
        //            dp.userId = script.Substring(script.IndexOf("userId"), 30).Split(new char[] { ':', ',', '"' })[3];
        //            dp.nickname = System.Web.HttpUtility.UrlDecode(script.Substring(script.IndexOf("user_nick"), 100).Split(new char[] { ':', ',', '"' })[3]);
        //            dp.sjName = System.Web.HttpUtility.UrlDecode(script.Substring(script.IndexOf("design_nick"), 100).Split(new char[] { ':', ',', '"' })[3]);
        //        }
        //        catch (Exception ex)
        //        {
        //            GlobalFun.Write("err.log", false, htmlContent);
        //            System.Windows.Forms.MessageBox.Show(ex.Message);
        //            return null;
        //        }
        //        if (title.Contains("天猫Tmall.com"))
        //        {
        //            dp.dpXy = "";
        //            dp.dpVer = "天猫店铺";
        //            dp.createTime = "";
        //        }
        //        if (title.Contains("淘宝网"))
        //        {
        //            //没有等级情况的考虑不够
        //            HtmlNodeCollection rankNodeCollection = htmlDoc.DocumentNode.SelectNodes("//img[@class='rank']");
        //            if (rankNodeCollection == null)
        //                dp.dpXy = "";
        //            else
        //                dp.dpXy = XyRank(rankNodeCollection[0].Attributes["src"].Value);
        //            dp.dpVer = DianpuVer(htmlContent);
        //            dp.createTime = CreateDianpuDate(htmlContent);
        //        }
        //    }
        //    if((!title.Contains("首页"))&&(!title.Contains("天猫Tmall.com")))
        //    {
        //        dp.shopTitle = title.Split('-')[0].Trim();
        //        try
        //        {
        //            dp.shopId = htmlContent.Substring(htmlContent.IndexOf("shopId"), 30).Split(new char[] { ':', ',', '"' })[3];
        //            dp.userId = htmlContent.Substring(htmlContent.IndexOf("userId"), 30).Split(new char[] { ':', ',', '"' })[2];
        //            HtmlNode node = htmlDoc.DocumentNode.SelectNodes("//div[@id='shop-info']")[0];
        //            dp.dpXy = XyRank(node.SelectNodes("//img[@class='rank']")[0].Attributes["src"].Value);
        //            dp.nickname = node.SelectNodes("//a[@class='hCard fn']")[0].InnerText;
        //            dp.createTime = htmlDoc.DocumentNode.SelectNodes("//div[@class='basic']/ul/li")[0].ChildNodes[1].InnerText;
        //            dp.sjName = "";
        //            dp.dpVer = "最原始版本";
        //        }
        //        catch (Exception ex)
        //        {
        //            GlobalFun.Write("err.log", false, htmlContent);
        //            System.Windows.Forms.MessageBox.Show(ex.Message);
        //            return null;
        //        }
        //    }
        //    dp.dpURL = "http://shop" + dp.shopId + ".taobao.com";

        //    dp.kefu = "";
        //    dp.hanye = "";
        //    dp.dgTime = DateTime.Now;
        //    dp.cjTime = DateTime.Now;
        //    return dp;
        //}

        //private string CreateDianpuDate(string html)
        //{
        //    HtmlAgilityPack.HtmlDocument htmlDoc=ParseToHtml(html);
        //    string createTime="";
        //    //此处如此判断会有问题，有时候可能页面含有这样的串。不科学的方法，分析两者的页面可知，
        //    //对于老的店铺含有“店铺信息”有这样节结点<div class="shop-details"><h4>店铺信息</h4>
        //    //新的店铺有<div class="bd-left shop-intro">
        //    HtmlNodeCollection hncOld=htmlDoc.DocumentNode.SelectNodes("//div[@class='shop-details']");
        //    HtmlNodeCollection hncNew = htmlDoc.DocumentNode.SelectNodes("//div[@class='bd-left shop-intro']");

        //    if (hncOld!=null)
        //    {
        //        createTime=htmlDoc.DocumentNode.SelectNodes("//li[@class='setuptime']")[0].ChildNodes[1].InnerText;
        //    }
        //    if (hncNew!=null)
        //    {
        //        createTime = htmlDoc.DocumentNode.SelectNodes("//div[@class='bd-left shop-intro']")[0].SelectNodes("//span[@class='text']")[3].InnerText;
        //        string[] time = createTime.Split('年', '月', '日');
        //        createTime = time[0] + "-" + time[1] + "-" + time[2];
        //    }
        //    return createTime;
        //}
        ///// <summary>
        ///// 根据页面信息得到相应的版本  
        ///// </summary>
        ///// <param name="ver">传入的HTML信息</param>
        ///// <returns>2012新旺铺专业版   2012新旺铺基础版  天猫店铺  旺铺扶植版  旺铺标准版  旺铺拓展版  旺铺旗舰版</returns>
        //public string DianpuVer(string html)
        //{
        //    string retVer = "";
        //    if (html.Contains("http://img04.taobaocdn.com/tps/i4/T1prA2XhlhXXcgU5U6-113-21.png"))
        //        retVer = "2012新旺铺基础版";
        //    else if (html.Contains("http://img01.taobaocdn.com/tps/i1/T1lKXaXp4hXXcgU5U6-113-21.png"))
        //        retVer = "2012新旺铺专业版";
        //    else if (html.Contains("标准版"))
        //        retVer = "旺铺标准版";
        //    else if (html.Contains("扶植版"))
        //        retVer = "旺铺扶植版";
        //    else if (html.Contains("拓展版"))
        //        retVer = "旺铺拓展版";
        //    else if (html.Contains("旗舰版"))
        //        retVer = "旺铺旗舰版";
        //    else
        //        retVer = "天猫店铺";
        //    return retVer;
        //}

        ///// <summary>
        ///// 根据传的img src=""图片属性得到信用等级图片，本地存储，加快网络速度。
        ///// 如 http://pics.taobaocdn.com/newrank/s_blue_5.gif
        /////    http://pics.taobaocdn.com/newrank/s_red_4.gif
        /////    http://pics.taobaocdn.com/newrank/s_crown_1.gif
        ///// </summary>
        ///// <param name="rankURL"></param>
        ///// <returns></returns>
        //public string XyRank(string rankURL)
        //{
        //    string levelImg = rankURL.Split('/')[4];
        //    return levelImg;
        //}
        #endregion       
    }
}
